<template>
  <el-container>
    <el-aside width="320px">
      <div class="question-choice">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>问题类型</span>
            </div>
          </template>
          <div
            v-for="item in choiceList"
            :key="item.name"
            class="text-item"
            @click="item.func"
          >
            <i :class="item.icon"></i>
            <span class="choice-name"> {{ item.name }} </span>
          </div>
        </el-card>
      </div>
    </el-aside>
    <el-main>
      <el-card class="main-area">
        <div class="card-content">
          <!-- 标题输入框 -->
          <el-input
            v-model="questionnaire.title"
            placeholder="请输入问卷标题"
            maxlength="20"
            minlength="1"
            show-word-limit
            class="title"
            @change="postHead"
          ></el-input>
          <!-- 描述输入框 -->
          <el-input
            type="textarea"
            :rows="3"
            :autosize="true"
            placeholder="请输入内容"
            v-model="questionnaire.desc"
            maxlength="100"
            class="title"
            show-word-limit
            @change="postHead"
          >
          </el-input>
          <!-- 问卷内容填充处 -->
          <draggable
            class="dragArea list-group w-full"
            :list="questionnaire.questions"
            @change="changeOrder"
          >
            <div
              v-for="(question, index) in questionnaire.questions"
              :key="index"
              class="question-fill-content"
            >
              <single-choice-done
                v-if="question.type === 'single'"
                :question="question"
                :number="index + 1"
                :getQuestionnaire="getQuestionnaire"
                :questionnaire_id="questionnaire_id"
                :addQuestion="addQuestion"
              ></single-choice-done>
              <multi-choice-done
                v-if="question.type === 'multi'"
                :question="question"
                :number="index + 1"
                :getQuestionnaire="getQuestionnaire"
                :questionnaire_id="questionnaire_id"
                :addQuestion="addQuestion"
              ></multi-choice-done>
              <fill-blank-done
                v-if="question.type === 'fill'"
                :question="question"
                :number="index + 1"
                :getQuestionnaire="getQuestionnaire"
                :questionnaire_id="questionnaire_id"
                :addQuestion="addQuestion"
              ></fill-blank-done>
            </div>
          </draggable>

          <!-- 用户正在编辑的问卷内容 -->
          <div v-if="type === 'single'">
            <single-choice
              :class="{ shake: noActivated }"
              :closePanel="closePanel"
              :questionnaire_id="questionnaire_id"
              :getQuestionnaire="getQuestionnaire"
              :addQuestion="addQuestion"
            ></single-choice>
          </div>
          <div v-if="type === 'multi'">
            <multi-choice
              :class="{ shake: noActivated }"
              :closePanel="closePanel"
              :questionnaire_id="questionnaire_id"
              :getQuestionnaire="getQuestionnaire"
              :addQuestion="addQuestion"
            ></multi-choice>
          </div>
          <div v-if="type === 'fill'">
            <fill-blank
              :class="{ shake: noActivated }"
              :closePanel="closePanel"
              :questionnaire_id="questionnaire_id"
              :getQuestionnaire="getQuestionnaire"
              :addQuestion="addQuestion"
            ></fill-blank>
          </div>
        </div>
      </el-card>
    </el-main>
  </el-container>
</template>

<script>
  import axios from "axios";
  import FillBlank from "./Choices/FillBlank.vue";
  import MultiChoice from "./Choices/MultiChoice.vue";
  import SingleChoice from "./Choices/SingleChoice.vue";
  import FillBlankDone from "./Done/FillBlankDone.vue";
  import MultiChoiceDone from "./Done/MultiChoiceDone.vue";
  import SingleChoiceDone from "./Done/SingleChoiceDone.vue";
  import { VueDraggableNext } from "vue-draggable-next";

  export default {
    components: {
      SingleChoice,
      MultiChoice,
      FillBlank,
      FillBlankDone,
      MultiChoiceDone,
      SingleChoiceDone,
      draggable: VueDraggableNext,
    },
    props: {
      questionnaire_ids: Number,
    },
    data() {
      return {
        choiceList: [
          {
            name: "单选题",
            icon: "el-icon-success",
            func: this.addSingleChoice,
          },
          {
            name: "多选题",
            icon: "el-icon-s-claim",
            func: this.addMultiChoice,
          },
          {
            name: "填空题",
            icon: "el-icon-s-order",
            func: this.addFill,
          },
        ],
        // questionnaire: null,
        questionnaire: {
          title: "问卷标题",
          desc: "为了给您提供更好的服务，希望您能抽出几分钟时间，将您的感受和建议告诉我们，我们非常重视每位用户的宝贵意见，期待您的参与！现在我们就马上开始吧！",
          questions: [],
        },
        type: null, // 表示侧边栏的选项是否可以点击 如果已经选了 则不可以再点
        noActivated: false,
        timerShake: null,
        questionnaire_id: null,
        timer: null,
      };
    },
    beforeUnmount() {
      this.timer = null;
    },
    methods: {
      addSingleChoice() {
        if (!this.type) {
          this.type = "single";
        } else {
          this.noActivated = true;
          clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            this.noActivated = false;
          }, 1000);
        }
      },
      addMultiChoice() {
        if (!this.type) {
          this.type = "multi";
        } else {
          this.noActivated = true;
          clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            this.noActivated = false;
          }, 1000);
        }
      },
      addFill() {
        if (!this.type) {
          this.type = "fill";
        } else {
          this.noActivated = true;
          clearTimeout(this.timer);
          this.timer = setTimeout(() => {
            this.noActivated = false;
          }, 1000);
        }
      },
      closePanel() {
        this.type = null;
      },
      async postHead() {
        const form = {
          questionnaire_id: this.questionnaire_id,
          username: localStorage.getItem("username"),
        };
        var breakfunc = false
        await axios.post("isallowed/", form).then((response) => {
          // console.log('yessss')
          if (response.data.code == -3) {
            // 发布中不许改
            this.$notify.error({
              title: "错误",
              message: "问卷正处于发布状态，无法编辑",
            });
            this.getQuestionnaire();
            console.log('我摊牌了')
            breakfunc = true
          } else if (response.data.code == -4) {
            // 该问卷已被浏览过 请在副本中编辑
            this.$notify({
              title: "警告",
              message: "该问卷已被浏览，无法编辑，请在已自动复制的副本中进行编辑",
              type: "warning",
            });
            this.getQuestionnaire();
            breakfunc = true
          }
        });
        if(breakfunc) {return}
        const formData = {
          questionnaire_id: this.questionnaire_id,
          username: localStorage.getItem("username"),
          title: this.questionnaire.title,
          desc: this.questionnaire.desc,
        };
        console.log(formData);
        await axios.post("questionnaires/", formData).then((response) => {
          console.log(response.status);
          console.log(response.data);
        });
      },
      async getQuestionnaire() {
        // 获取问卷列表
        const formData = {
          questionnaire_id: this.questionnaire_id,
        };
        await axios.post("preview/", formData).then((response) => {
          this.questionnaire = response.data;
          this.questionnaire["questionnaire_id"] = this.questionnaire_id;
          console.log("传回来的问卷");
          console.log(this.questionnaire);
        });
      },
      async changeOrder() {
        const formData = {
          questionnaire_id: this.to,
          username: localStorage.getItem("username"),
        };
        var breakfunc = false
        await axios.post("isallowed/", formData).then((response) => {
          // console.log('yessss')
          if (response.data.code == -3) {
            // 发布中不许改
            this.$notify.error({
              title: "错误",
              message: "问卷正处于发布状态，无法编辑",
            });
            this.getQuestionnaire();
            console.log('我摊牌了')
            breakfunc = true
          } else if (response.data.code == -4) {
            // 该问卷已被浏览过 请在副本中编辑
            this.$notify({
              title: "警告",
              message: "该问卷已被浏览，无法编辑，请在已自动复制的副本中进行编辑",
              type: "warning",
            });
            this.getQuestionnaire();
            breakfunc = true
          }
        });
        if(breakfunc) {return}
        await axios
          .post("sendQuestionnaire/", this.questionnaire)
          .then((response) => {
            console.log("改变之后的问卷");
            console.log(this.questionnaire);
            console.log(response.data);
          });
      },
      async addQuestion(question) {
        const formData = {
          questionnaire_id: this.to,
          username: localStorage.getItem("username"),
        };
        var breakfunc = false
        await axios.post("isallowed/", formData).then((response) => {
          // console.log('yessss')
          if (response.data.code == -3) {
            // 发布中不许改
            this.$notify.error({
              title: "错误",
              message: "问卷正处于发布状态，无法编辑",
            });
            this.getQuestionnaire();
            console.log('我摊牌了')
            breakfunc = true
          } else if (response.data.code == -4) {
            // 该问卷已被浏览过 请在副本中编辑
            this.$notify({
              title: "警告",
              message: "该问卷已被浏览，无法编辑，请在已自动复制的副本中进行编辑",
              type: "warning",
            });
            this.getQuestionnaire();
            breakfunc = true
          }
        });
        if(breakfunc) {return}
        this.questionnaire.questions.push(question);
        console.log("here1");
        console.log(question);
        console.log(this.questionnaire);
        await axios
          .post("sendQuestionnaire/", this.questionnaire)
          .then((response) => {
            console.log(response.data);
          });
        await this.getQuestionnaire();
      },
    },
    async created() {
      this.questionnaire_id = this.questionnaire_ids;
      this.to = this.questionnaire_ids;
      if (typeof this.questionnaire_id == "string") {
        await axios
          .post("decode/", {
            questionnaire_id: this.questionnaire_id,
          })
          .then((response) => {
            if (response.data.code == -1) {
              this.$router.push({
                path: "/failure",
                query: {
                  msg: "该问卷不存在或您没有权限访问",
                },
              });
            }
            this.questionnaire_id = response.data.id;
          });
      }
      await this.getQuestionnaire();
      if (this.questionnaire.questions.length == 0) {
        const question1 = {
          id: null,
          must: true,
          question_id: null,
          questionnaire_id: this.questionnaire_id,
          remark: "请填写您的学号",
          row: "1",
          title: "学号",
          type: "fill",
          username: this.questionnaire.username,
        };
        const question2 = {
          id: null,
          must: true,
          question_id: null,
          questionnaire_id: this.questionnaire_id,
          remark: "请填写您的姓名",
          row: "1",
          title: "姓名",
          type: "fill",
          username: this.questionnaire.username,
        };
        const question3 = {
          title: "体温",
          type: "single",
          remark: "",
          must: true,
          options: [
            {
              title: "低于36.1℃",
            },
            {
              title: "36.1~37.2℃",
            },
            {
              title: "37.3~38℃",
            },
            {
              title: "38.1~42℃",
            },
            {
              title: "高于42℃",
            },
          ],
        };
        const question4 = {
          title: "有无去过高风险地区",
          type: "single",
          remark: "",
          must: true,
          options: [
            {
              title: "有",
            },
            {
              title: "无",
            },
          ],
        };
        const question5 = {
          title: "有无新冠症状",
          type: "single",
          remark: "",
          must: true,
          options: [
            {
              title: "有",
            },
            {
              title: "无",
            },
          ],
        };
        const question6 = {
          title: "定位",
          type: "fill",
          remark: "",
          must: true,
          row: 1,
          is_positioning: true,
        };
        await this.addQuestion(question1);
        await this.addQuestion(question2);
        await this.addQuestion(question3);
        await this.addQuestion(question4);
        await this.addQuestion(question5);
        await this.addQuestion(question6);
      }
    },
  };
</script>

<style scoped>
.el-container {
  font-family: "微软雅黑";
}

.box-card,
.question-choice {
  height: 100%;
}

.text-item {
  margin-bottom: 3px;
  cursor: pointer;
  padding-left: 5px;
  font-size: 14px;
  border: 1px solid #e0e0e0;
  height: 38px;
  line-height: 38px;
  align-items: center;
}

.choice-name {
  font-family: "PingFang SC", tahoma, arial, "helvetica neue",
    "hiragino sans gb", "microsoft yahei ui", "microsoft yahei", simsun,
    sans-serif;
  margin-left: 7px;
}

.main-area {
  padding-top: 80px;
  padding-bottom: 100px;
}

.card-content {
  width: 70%;
  margin: 0 auto;
}

.el-input,
.el-textarea {
  margin-bottom: 20px;
}

.question-fill-content {
  margin-top: 20px;
  margin-bottom: 20px;
  font-size: 14px;
}

.shake {
  animation: shake 0.82s cubic-bezier(0.36, 0.07, 0.19, 0.97) both;
  transform: translate3d(0, 0, 0);
  backface-visibility: hidden;
  perspective: 1000px;
}

@keyframes shake {
  10%,
  90% {
    transform: translate3d(-1px, 0, 0);
  }

  20%,
  80% {
    transform: translate3d(2px, 0, 0);
  }

  30%,
  50%,
  70% {
    transform: translate3d(-4px, 0, 0);
  }

  40%,
  60% {
    transform: translate3d(4px, 0, 0);
  }
}
</style>